package fr.sedoo.metadata.client.ui.view;

import java.util.Iterator;
import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Widget;

import fr.sedoo.commons.client.message.CommonMessages;
import fr.sedoo.commons.client.widget.DialogBoxTools;
import fr.sedoo.commons.shared.domain.HasIdentifier;
import fr.sedoo.metadata.client.ui.widget.table.format.FormatTable;
import fr.sedoo.metadata.client.ui.widget.table.misc.HasIdentifierWrapper;
import fr.sedoo.metadata.client.ui.widget.table.misc.HasIdentifierWrapperList;
import fr.sedoo.metadata.shared.domain.dto.FormatDTO;

public class FormatListViewImpl extends AbstractSection implements FormatListView {

	private static FormatListViewImplUiBinder uiBinder = GWT.create(FormatListViewImplUiBinder.class);

	interface FormatListViewImplUiBinder extends UiBinder<Widget, FormatListViewImpl> {
	}

	private Presenter presenter;

	public FormatListViewImpl() {
		super();
		initWidget(uiBinder.createAndBindUi(this));
		applyCommonStyle();
		formatTable.setAddButtonEnabled(true);
		formatTable.init(new HasIdentifierWrapperList());
	}

	@Override
	public void setFormats(List<FormatDTO> formats) {
		formatTable.init(new HasIdentifierWrapperList(formats));

	}

	@UiField
	FormatTable formatTable;

	@Override
	public void broadcastFormatDeletion(Long formatId, boolean success) {
		if (success) {
			String id = getIdByFormatid(formatId);
			formatTable.removeRow(id);
		} else {
			DialogBoxTools.modalAlert(CommonMessages.INSTANCE.error(), CommonMessages.INSTANCE.anErrorHasOccurred());
		}
	}

	private String getIdByFormatid(Long formatId) {
		Iterator<? extends HasIdentifier> iterator = formatTable.getModel().iterator();
		while (iterator.hasNext()) {
			HasIdentifierWrapper wrapper = (HasIdentifierWrapper) iterator.next();
			FormatDTO format = (FormatDTO) wrapper.getSrc();
			if (format.getId().compareTo(formatId) == 0) {
				return wrapper.getIdentifier();
			}
		}
		return "" + -1L;
	}

	@Override
	public void setPresenter(Presenter presenter) {
		this.presenter = presenter;
		formatTable.setPresenter(presenter);
	}

}
